package com.example.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author: 21050134
 * @date: 2023/11/1 16:55
 * @description:
 */
@Controller
public class MyController {
	@RequestMapping({"/","/index"})
	public String toIndex(Model model){
		model.addAttribute("msg","hello,Shiro");
		return "index";
	}

	@RequestMapping("/toAdd")
	public String toAdd(){
		return "user/add";
	}

	@RequestMapping("/toUpdate")
	public String toUpdate(){
		return "user/update";
	}

	@RequestMapping({"/toLogin"})
	public String toLogin(){
		return "login";
	}

	@RequestMapping({"/login"})
	public String login(String userName,String password,Integer rememberMe,Model model){
		//使用shiro,编写认证操作
		//1.获取Subject
		Subject subject = SecurityUtils.getSubject();
		//2.封装用户的数据
		UsernamePasswordToken token = new UsernamePasswordToken(userName,password);
		if(rememberMe!=null&&rememberMe==1){
			token.setRememberMe(true);
		}
		//3.执行登陆方法，只要没有异常就代表登陆成功
		try{
			subject.login(token);
			return "index";
		}catch (UnknownAccountException e){
			model.addAttribute("msg","用户名不存在");
			return "login";
		}catch (IncorrectCredentialsException e){
            model.addAttribute("msg","密码错误");
            return "login";
		}
	}

	@RequestMapping("/noauth")
	@ResponseBody
	public String noAuth(){
		return "未经授权不能访问此页面";
	}


	@RequestMapping("/logout")
	public String logout(){

		Subject subject = SecurityUtils.getSubject();
		subject.logout();
		return "index";
	}

	//用于测试记住我和认证的区别
	@RequestMapping("/buy")
	public String buy(){
		Subject subject = SecurityUtils.getSubject();
		//只有认证后才能访问，如果只是记住我则需要先登录
		if(!subject.isAuthenticated()){
			return "redirect:/toLogin";
		}
		return "user/add";
	}


}
